package com.wanghlme.day27.dao.impl;

import com.wanghlme.day27.dao.IEmpDao;
import com.wanghlme.day27.pojo.Dept;
import com.wanghlme.day27.pojo.Emp;
import com.wanghlme.day27.util.IRowWrapper;
import com.wanghlme.day27.util.JdbcTemplate;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class EmpDaoImpl implements IEmpDao {
    private JdbcTemplate<Emp> template;

    public EmpDaoImpl() {
        template = new JdbcTemplate<>();
    }

    private class EmpRowWrapper implements IRowWrapper<Emp> {

        @Override
        public Emp transfer(ResultSet rs) throws SQLException {
            if (rs == null) {
                return null;
            }
            Emp emp = new Emp();
            emp.setEmpHiredate(rs.getTimestamp("emp_hiredate"));
            emp.setEmpId(rs.getInt("emp_id"));
            emp.setEmpName(rs.getString("emp_name"));
            emp.setEmpStatus(rs.getInt("emp_status"));
            Dept dept = new Dept();
            dept.setDeptId(rs.getInt("dept_id"));
            emp.setDept(dept);
            return emp;
        }
    }


    @Override
    public List<Emp> listAllEmp() {
        String sql = "select emp_id, emp_name, emp_hiredate, dept_id, emp_status from emp";
        return template.queryForList(sql, null, new EmpRowWrapper());
    }

    @Override
    public Emp queryEmpById(Integer id) {
        String sql = "select emp_id, emp_name, emp_hiredate, dept_id, emp_status from emp where emp_id = ?";
        return template.queryForOne(sql, new Object[]{id}, new EmpRowWrapper());
    }

    @Override
    public Integer updateEmp(Emp emp) {
        if (emp == null) {
            return -1;
        }
        String sql = "update emp set emp_name = ?, emp_hiredate = ?, dept_id = ? where emp_id = ?";
        return template.executeUpdate(sql, new Object[]{
                emp.getEmpName(),
                emp.getEmpHiredate(),
                emp.getDept().getDeptId(),
                emp.getEmpId()
        });
    }

    @Override
    public Integer updateEmpStatus(Integer id, Integer empStatus) {
        String sql = "update emp set emp_status = ? where emp_id = ?";
        return template.executeUpdate(sql, new Object[]{empStatus, id});
    }

    @Override
    public Integer insertEmp(Emp emp) {
        if (emp == null) {
            return -1;
        }
        String sql = "insert into emp(emp_name, emp_hiredate, dept_id) values (?, ?, ?)";
        return template.executeUpdateReturnId(sql, new Object[]{
                emp.getEmpName(),
                emp.getEmpHiredate(),
                emp.getDept().getDeptId()
        });
    }

    @Override
    public Integer deleteEmp(Integer id) {
        String sql = "delete from emp where emp_id = ?";
        return template.executeUpdate(sql, new Object[]{id});
    }


}
